package github.leavesczy.reactivehttpsamples.ui.addbridge

import android.os.Bundle
import android.util.Pair
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import github.leavesczy.reactivehttpsamples.base.BaseActivity
import github.leavesczy.reactivehttpsamples.core.mode.BridgeRecordItem
import github.leavesczy.reactivehttpsamples.core.viewmodel.addbridge.AddBridgeModel
import github.leavesczy.reactivehttpsamples.databinding.ActivityBridgeAddBinding
import github.leavesczy.reactivehttpsamples.ui.addbridge.func.BridgeFunction
import github.leavesczy.reactivehttpsamples.util.BridgeDataHelper
import github.leavesczy.reactivehttpsamples.util.Logger
import github.leavesczy.reactivehttpsamples.util.exception.BusException
import github.leavesczy.reactivehttpsamples.widget.dialog.CommonDialogContent

class BridgeAddActivity : BridgeFunction, BaseActivity() {

    override val bind by getBind<ActivityBridgeAddBinding>()

    private val viewModel by getViewModel<AddBridgeModel>() {
        bridgeAdd.observe(this@BridgeAddActivity) {
            showToast("处理成功")
            this@BridgeAddActivity.finish()
        }

        bridgeDetail.observe(this@BridgeAddActivity) {
           //桥梁详情
            itemData=it
            initView()
        }
    }

    private val fragments = mutableListOf<Fragment>()
    private val titles = mutableListOf<String>()

    private var itemData: BridgeRecordItem? = null

    private var forbiddenEdit=false

    private var editable=true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initData()
        initListener()

        if(itemData==null){
            initView()
        }
        itemData?.let {
            viewModel.requestBridgeDetail(it.recordId)
        }

    }


    private fun initListener() {
        bind.headerView.initBack{
            //左侧的返回，需要判断内容是否有变更
            if(checkContentChange()){
                CommonDialogContent().init(this,
                    "提醒",
                    "是否保存修改内容？",
                    Pair("是", View.OnClickListener {
                        try {
                            sendAddRequest()
                        } catch (buEc: BusException) {
                            ToastUtils.showShort(buEc.message)
                        }

                    }),
                    Pair("否", View.OnClickListener {
                        ActivityUtils.finishActivity(this)
                    })
                ).show("CommonDialogContent")

            }else{
                ActivityUtils.finishActivity(this)
            }

        }

        //右侧保存
        bind.headerView.initRightText("保存"){
            //需要判断是否允许保存
            if(!this.editable){
                showToast("当前状态只能查看，无法编辑保存")
                return@initRightText
            }
            try {
                sendAddRequest()
            } catch (buEc: BusException) {
                ToastUtils.showShort(buEc.message)
            }
        }
    }

    private fun checkContentChange():Boolean{
        //当前页面不可编辑，那内容肯定是没变动的
        if(!this.editable){
            return false
        }
        try {
            check()
            //正常走下来了代表 内容没有变化
            return false
        }catch (buEc:BusException){
            return true
        }

    }

    override fun check(){
        checkText(bind.tfBridgeName,itemData?.bridgeName)
        checkText(bind.tfBridgeCode,itemData?.bridgeCode)
        checkSpinner(bind.bsBridgeType,itemData?.bridgeType.toString())


        fragments.forEach {
            if (it is BridgeFunction) {
                it.check()
            }
        }

    }

    private fun sendAddRequest() {
        //请求
        val paramMap = mutableMapOf<String, Any>()
        itemData?.let {
            paramMap.put("recordId", it.recordId)
        }
        addTextFieldParam(paramMap, bind.tfBridgeName, "bridgeName", "桥梁名称")
        addTextFieldParam(paramMap, bind.tfBridgeCode, "bridgeCode", "桥梁编码")
        addSpinnerParam(paramMap, bind.bsBridgeType, "bridgeType", "请选择桥梁类型")

        fragments.forEach {
            if (it is BridgeFunction) {
                it.dealRequestParam(paramMap)
            }
        }

        //请求网络
        viewModel.requestBridgeAdd(paramMap)
    }


    private fun initView() {
        bind.headerView.init(this)

        initTabViewPage()

        bind.bsBridgeType.setItems(BridgeDataHelper.getBridgeTypeList())
        bind.bsBridgeType.setSelectCallback {
            Logger.d("桥梁类型选择：${it.name}")
            //切换类型后，需要主动刷新当前展示的页面，其他未展示的，会在显示的时候主动处理更新桥梁类型
            (fragments.get(bind.viewPageBridgeAdd.currentItem) as? BridgeFunction)?.refreshBridgeType()
        }


        itemData?.let {
            setBridgeData(it)
        }

    }

    private fun  setBridgeData(it:BridgeRecordItem){
        bind.headerView.setTitle(it.bridgeName)
        val editable = !this.forbiddenEdit && it.isCanAnalysis()
        dealTextField(bind.tfBridgeName,it.bridgeName,editable)
        dealTextField(bind.tfBridgeCode,it.bridgeCode,editable)
        dealSpinner(bind.bsBridgeType,it.bridgeType.toString(),editable)

        this.editable=editable
    }

    private fun initData() {
        val bundle = intent.extras
        itemData = bundle?.getSerializable("item") as? BridgeRecordItem
        //是否禁用编辑功能
        forbiddenEdit= bundle?.getBoolean("forbiddenEdit",false)?:false

        bind.headerView.setTitle("新增桥梁档案")

    }

    private fun initTabViewPage() {

        fragments.clear()
        fragments.add(CaeModelBridge.newInstance(itemData))
        fragments.add(PreEvaluationModelBridge.newInstance(itemData))
        fragments.add(DataAnalysisModelBridge.newInstance(itemData))

        titles.clear()
        titles.add("有限元模型")
        titles.add("神经网络")
        titles.add("车载数据分析")


        bind.viewPageBridgeAdd.offscreenPageLimit = fragments.size
        bind.viewPageBridgeAdd.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItemPosition(`object`: Any): Int {
                return super.getItemPosition(`object`)
            }

            override fun getPageTitle(position: Int): CharSequence {
                return titles.get(position)
            }

            override fun getCount(): Int {
                return fragments.size
            }

            override fun getItem(position: Int): Fragment {
                return fragments.get(position)
            }

        }
        bind.tabBridgeAdd.setupWithViewPager(bind.viewPageBridgeAdd)
    }


    fun getBridgeType(): String {

        val value = bind.bsBridgeType.select
        //默认桥梁类型 就是当前的1
        return value?.value ?: "1"
    }

    fun getForbiddenEdit():Boolean{
        return forbiddenEdit
    }
    fun getBridgeCode():String?{
        return bind.tfBridgeCode.editTextStr
    }

    fun getSpanMax(): String? {
        var result:String?=null
        fragments.forEach {
            if(it is CaeModelBridge){
                result = it.getSpanMax()
            }
        }

        return result
    }

    fun getTowerNumber(): String? {
        var result:String?=null
        fragments.forEach {
            if(it is CaeModelBridge){
                result = it.getTowerNumber()
            }
        }

        return result
    }

    fun getTowerHeightTotal(): String? {
        var result:String?=null
        fragments.forEach {
            if(it is CaeModelBridge){
                result = it.getTowerHeightTotal()
            }
        }

        return result
    }

    fun getMainBeamType(): String? {
        var result:String?=null
        fragments.forEach {
            if(it is CaeModelBridge){
                result = it.getMainBeamType()
            }
        }

        return result
    }
}